﻿
/*=========================================
* Author: Administrator
* DateTime:2017/6/21 12:43:50
* Description:$safeprojectname$
==========================================*/

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

namespace OrderSystem
{
    public class ClientView : MonoBehaviour
    {
        public UnityAction<ClientItem> LeaveClient = null;
        public UnityAction<ClientItem> CallWaiter = null;
        public UnityAction<ClientItem> PayWaiter = null;
        private ObjectPool<ClientItemView> objectPool = null;
        private List<ClientItemView> clientViewItems = new List<ClientItemView>();
        private Transform parent = null;

        private void Awake()
        {
            parent = this.transform.Find("Content");
            var prefab = Resources.Load<GameObject>("Prefabs/UI/ClientItem");
            objectPool = new ObjectPool<ClientItemView>(prefab , "ClientPool");
        }

        public void UpdateClient( IList<ClientItem> clientsData )
        {
            if (clientsData == null)
            {
                Debug.Log("没有数据,client状态无法进行更新");
                return;

            }
            for (int i = 0; i < this.clientViewItems.Count; i++)
                objectPool.Push(this.clientViewItems[i]);
              //进行清除
              //重新加入
            this.clientViewItems.AddRange(objectPool.Pop(clientsData.Count));
            
            for ( int i = 0 ; i < this.clientViewItems.Count ; i++ )
            {
                if (i <clientsData.Count)
                {
                   
                    this.clientViewItems[i].gameObject.SetActive(true);
                    var client = this.clientViewItems[i];
                    client.transform.SetParent(parent);
                    client.InitClient(clientsData[i], PayWaiter, LeaveClient);                  
                    client.GetComponent<Button>().onClick.RemoveAllListeners();
                    client.GetComponent<Button>().onClick.AddListener(() => {
                        Debug.Log("1.点击" + client.clientData.id + "桌子下单");
                        CallWaiter(client.clientData);
                    });
                }               
            }
        }
        public void UpdateState( ClientItem client )
        {
            for (int i = 0; i < clientViewItems.Count; i++)
            {
                if (clientViewItems[i].clientData.id.Equals(client.id))
                {
                    clientViewItems[i].InitClient(client, PayWaiter,LeaveClient);                  
                    return;
                }
            }
        }
    }
}